package aeduclient;

import aeducommon.GameModel;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Adrian Hostettler
 */
class Client implements Observer, Runnable {

    String hostName;
    int nameExchangePort;
    int gameExchangePort;
    NameClientConn nameConn;
    GameClientConn gameConn;
    Socket nameExchangeSocket = null;
    Socket gameExchangeSocket = null;
    int playerId;
    GameModel gameModel;
    Gui gui;

    void doYourStuff() {
        this.run();
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o.equals(gameConn)) {
            this.gameModel = (GameModel) arg;
            updateGui(gameModel);
        } else if (o.equals(nameConn)) {
            establishGameConn();
        }
    }

    private void updateGui(GameModel gm) {
        if (gui == null) {
            gui = new Gui(gm, nameConn.getPlayerId());
        } else {
            gui.updateGui(gm);
        }
    }

    private void establishGameConn() {
        try {
            gameExchangeSocket = new Socket(hostName, gameExchangePort);
        } catch (UnknownHostException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        gameConn = new GameClientConn(gameExchangeSocket);
    }

    @Override
    public void run() {

        gui = null;
        hostName = "";
        nameExchangePort = 2222;
        gameExchangePort = 5555;
        try {
            System.out.println("\ntry to open socket on " + hostName + " on port " + nameExchangePort + "\n");
            nameExchangeSocket = new Socket("", 2222);

            nameConn = new NameClientConn(nameExchangeSocket);
            nameConn.addObserver(this);

        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: localhost. ->" + e);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: localhost.->" + e);
            System.exit(1);
        }
        while(true){
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}